<?php
/*
v1.00
bach
2017-01-12
D(Email)->send($demand,$data);
*/

namespace app\common\model;
use think\Model;
class Email extends Model {

    private $config;
    private $isEn = false;
    function __construct(){
        $this->account = config('email');
        $this->config = getConfig('email',1);
    }
    private function channel__sih($demand,$data){
        $to = $data['email'];
        $userName = $data['userName'];
        $title = $data['title'];
        $template = $data['template'];
        $tel = $data['tel'];
        //开始启用hongyanche肥皂结构发送
        header("content-type:text ml;charset=utf-8");
        $client = new \SoapClient("http://ws.sih.cq.cn/sihwebservice/sendmail/sendmail.asmx?wsdl");
        $send = array(
            'key'=>"89418D76-0BB7-4311-B8EC-C3B79F6978C0",
            'strReceiver'=>$to,
            'strSubject'=>$title,
            'strContent'=>$template
            );
        $return = $client->SendEmailWithHtml($send);
        $return = json_decode(json_encode($return),1);
        $reason = $return['SendMessageResult']['reason'];
        if( strstr($reason,$tel) ){
            $ret = array('state'=>1,'errormsg'=>'sms send success');
        }else{
            $ret = array('state'=>0,'errormsg'=>$reason,'data'=>$return);

        }
        return $ret;
    }
    private function channel__alimail($demand,$data){
        $account    = $this->account;
        $address    = $account["address"];
        $address = iconv("GB2312", "UTF-8//Ignore", $address);
        $password   = $account["password"];
        if($this->isEn) $fromName = $account['name_en'];
        if(!isset($fromName)) $fromName = $account['name'];
        $to = $data['email'];
        $title = $data['title'];
        $template = $data['template'];
        vendor("PHPMailer");
        $mail = new \PHPMailer;
        $mail->IsSMTP();                        // 启用SMTP
        $mail->Host = 'smtp.mxhichina.com';//$email_config['MAIL_HOST'];           //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = TRUE;   //启用smtp认证
        $mail->Username = $address;   //你的邮箱名
        $mail->Password = $password;   //邮箱密码
        $mail->From     = $address;    //发件人地址（也就是你的邮箱地址）
        $mail->FromName = $fromName;   //发件人姓名
//        $mail->SMTPSecure = 'ssl';
//        $mail->Port       = 465;
        $mail->SMTPDebug  = 1;
        $mail->AddAddress($to, $userName = null);   //
        $mail->WordWrap = 50;                   //设置每行字符长度
        $mail->IsHTML(true);        // 是否HTML格式邮件
        $mail->CharSet = "utf-8";     //设置邮件编码
        $mail->Subject = $title;                //邮件主题
        $mail->Body = $template;                //邮件内容
        $mail->AltBody = $title; //邮件正文不支持HTML的备用显示
        $res = $mail->Send();
        if($res !== true){
            return ["state"=>0,"errormsg"=>$mail->ErrorInfo];
        }
        $res = array('state'=>1);
        return $res;
    }
    private function channelSelect($demand, $data){
        $isEn = $this->isEn;
        if($isEn) $template_public = getTemplate("email/public_en",1);
        if(!isset($template_public)) $template_public = getTemplate("email/public",1);
        if(!isset($template_public) || !$template_public) return array('state'=>0,'errormsg'=>'template_public empty');
        if($isEn) $template = getTemplate("email/$demand"."_en",1);
        if(!isset($template)) $template = getTemplate("email/$demand");
        if(!isset($template) || !$template) return array('state'=>0,'errormsg'=>'template empty');

        $config = $this->config[$demand];
        if($isEn) $title=$config['title_en'];
        if(!isset($title)) $title=$config['title'];
        $s = $title;
        $i = strpos($s,"{\$");
        while($i){
            $ii = strpos($s,"}",$i);
            $e = substr($s,$i+2,$ii-$i-2);
            if(!isset($data[$e])){
                return array('state'=>0,'errormsg'=>"标题需要 $e");
            }
            $s = str_replace("{\$".$e."}",$data[$e],$s);
            $i = strpos($s,"{\$");
        }
        $data['title'] = $s;
        $s = $template;
        $i = strpos($s,'{$');
        while($i){
            $ii = strpos($s,"}",$i);
            $e = substr($s,$i+2,$ii-$i-2);
            if(!isset($data[$e])){
                return array('state'=>0,'errormsg'=>"模板需要 $e");
            }
            $s = str_replace('{$'.$e."}",$data[$e],$s);
            $i = strpos($s,'{$');
        }
        $data['template'] = str_replace('__CONTENT__', $s, $template_public);
        //channel
        $channel = $this->account['channel'];
        if(!$channel){
            return array('state'=>0,'errormsg'=>"邮箱不能为空");
        }
        $channel = 'channel__'.$channel;
        $res = $this->$channel($demand,$data);
        return $res;
    }
    public function send($demand, $data) {
        $config = $this->config;
        if(!isset($config)){
            return array('state'=>0,'errormsg'=>'配置错误');
        }
        if(!isset($config[$demand])){
            return array('state'=>0,'errormsg'=>'类别错误');
        }
        $config = $config[$demand];
        $cool = $config['cooldown_ip'];
        if(!$cool){
            return array('state'=>0,'errormsg'=>'ip cool error');
        }
        if(isset($data["isEn"])) $this->isEn = true;
        $cool     = explode(",",$cool);
        $during   = $cool[0];
        $limit    = $cool[1];
        $order    = "email_id desc";
        $classId = $config['id'];
        $field    = "create_time";
        $where  = array(
            "ip_remote"   => getIp(),
            "class" => $classId,
            );
        $res = db('email')->where($where)->field($field)->limit($limit-1,1)->order($order)->select();
        if(count($res)){
            $mostSendTime = $res[0]['create_time'];
            if($mostSendTime){
                $timePassed = time() - $mostSendTime;
                if( $timePassed < $during ){
                    $remain = $during - $timePassed;
                    return array('state'=>0,'errormsg'=>'this ip send too much','data'=>array('remain'=>$remain));
                }
            }
        }
        $email = $data['email'];
        if(!$email){
            return array('state'=>0,'errormsg'=>'email error');
        }
        $cooldown = (int)$config['cooldown'];
        $where  = array(
            "email" => $email ,
            "class" => $classId ,
            );
        if(!$cooldown){
            return array('state'=>0,'errormsg'=>'cool error');
        }
        $res = db('email')->where($where)->field($field)->order($order)->find();
        $lastSendTime = $res['create_time'];
        $timePassed = time() - $lastSendTime;
        if( $timePassed < $cooldown ){
            $remain = $cooldown - $timePassed;
            return array('state'=>0,'errormsg'=>'email cooling','data'=>array('remain'=>$remain));
        }
        $res = $this->channelSelect($demand,$data);
        if(!$res['state']){
            return $res;
        }
        $insert = array(
            'email'       => $email,
            'class'     => $config['id'],
            'create_time' => time(),
            'ip_remote'   => getIp(),
            );

        $res = db('email')->insertGetId($insert);
        $action = new Action;
        $action->add('email',$demand,$email);
        return array('state'=>1,'errormsg'=>'email send success');
    }

}
